package org.tangjl.multidatasource.dynamic;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据源配置
 *
 * @author tangjialin1@tcl.com on 2025-08-26.
 */
@Configuration
public class DataSourceConfiguration {
    /**
     * 主库数据源
     */
    @Bean(name = "primaryDataSource")
    @ConfigurationProperties("spring.datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 从库数据源
     */
    @Bean(name = "secondaryDataSource")
    @ConfigurationProperties("spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 动态数据源: 通过AOP在不同数据源之间动态切换
     */
    @Primary
    @Bean(name = "dataSource")
    public DataSource dataSource() {
        DataSource primaryDataSource = primaryDataSource();

        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setDefaultTargetDataSource(primaryDataSource);
        Map<Object, Object> dsMap = new HashMap<>();
        dsMap.put(DataSourceType.PRIMARY, primaryDataSource);
        dsMap.put(DataSourceType.SECONDARY, secondaryDataSource());
        dynamicDataSource.setTargetDataSources(dsMap);

        return dynamicDataSource;
    }

}
